import {Injectable} from '@angular/core';
import {AppConfig} from '../config';
import {Http, Headers} from '@angular/http';
import {MatrixState} from '../entity/matrix_state.model';
import {Observable} from 'rxjs/Observable';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class MatrixStateService {
  private readonly param = 'matrixStates';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }


  /**
   * 获得矩阵状态
   *
   * @returns {Promise<MatrixState[]>}
   * @memberof MatrixStateService
   */
  getMatrixStates(): Promise<MatrixState[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as MatrixState[])
      .catch(this.handleError);
  }

  /**
   * 根据状态分组ID获得矩阵状态
   *
   * @param {number} stateGroupid
   * @returns {Promise<MatrixState[]>}
   * @memberof MatrixStateService
   */
  getMatrixStatesByStateGroupid(stateGroupId: number): Promise<MatrixState[]> {
    return this.http.get(`${this.url}/stateGroupId/${stateGroupId}`)
      .toPromise()
      .then(response => response.data as MatrixState[])
      .catch(this.handleError);
  }

  create(matrixState: MatrixState): Promise<MatrixState> {
    return this.http.post(this.url, JSON.stringify(matrixState))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data as MatrixState;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  update(matrixState: MatrixState): Promise<MatrixState> {
    const url = `${this.url}`;
    return this.http.put(url, JSON.stringify(matrixState))
      .toPromise()
      .then(() => matrixState)
      .catch(this.handleError);
  }

  //根据Name判断是否已经存在
  hasStateName(stateName: string, stateGroupId: number, stateId: number): Observable<boolean> {
    const url = `${this.url}/stateName/${stateName}/stateId/${stateId}/stateGroupId/${stateGroupId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  //颜色是否重复
  hasStateColor(stateColor: string, stateId: number, stateGroupId: number,): Observable<boolean> {
    stateColor = stateColor.replace(/\#/, '%23');
    const url = `${this.url}/stateColor/${stateColor}/stateId/${stateId}/stateGroupId/${stateGroupId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }

    }).catch(this.handleError);
  }

  //删除
  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  //批量状态删除
  batchDelete(keyIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${keyIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

}


// WEBPACK FOOTER //
// ./src/app/service/matrix-state.service.ts
